package com.youkeda.dewu.service.impl;

import com.youkeda.dewu.dao.OrderDAO;
import com.youkeda.dewu.dataobject.OrderDO;
import com.youkeda.dewu.model.*;
import com.youkeda.dewu.param.QueryOrderParam;
import com.youkeda.dewu.service.OrderService;
import com.youkeda.dewu.service.ProductDetailService;
import com.youkeda.dewu.service.ProductService;
import com.youkeda.dewu.service.UserService;
import com.youkeda.dewu.util.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 刘正星
 * @version 1.0.0
 * @ClassName OrderServiceImpl.java
 * @Description TODO
 * @createTime 2020年10月09日 12:17:00
 */
@Service
public class OrderServiceImpl implements OrderService {
    private static final Logger LOG = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private ProductDetailService productDetailService;
    @Autowired
    private OrderDAO orderDAO;
    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;

    @Override
    public Order add(Order order) {
        if (order == null) {
            return null;
        }
        if (StringUtils.isEmpty(order.getProductDetailId())) {
            return null;
        }
        ProductDetail productDetail = productDetailService.getById(order.getProductDetailId());
        if (productDetail == null) {
            return null;
        }
        order.setProductDetail(productDetail);
        order.setTotalPrice(productDetail.getPrice());
        order.setId(UUIDUtils.getUUID());
        order.setOrderStatus(OrderStatus.WAIT_BUYER_PAY);
        //设置订单号
        order.setOrderNumber(getAutoId());
        OrderDO orderDO = new OrderDO(order);
        int add = orderDAO.insert(orderDO);
        if (add < 0) {
            return null;
        }
        return order;
    }

    @Override
    public Paging<Order> queryRecentPaySuccess(QueryOrderParam param) {
        Paging<Order> result = new Paging<>();
        if (param == null || StringUtils.isEmpty(param.getProductId())){
            return result;
        }
        if (param.getPageSize() < 0){
            param.setPageSize(0);
        }
        if (param.getPagination() < 0){
            param.setPagination(10);
        }
        int counts = orderDAO.selectCounts(param);
        if (counts < 0){
            return result;
        }
        result.setTotalCount(counts);
        result.setPageNum(param.getPagination());
        result.setPageSize(param.getPageSize());
        result.setTotalPage((int)Math.ceil(counts/param.getPageSize()*1.0));
        List<OrderDO> orderDOS = orderDAO.pageQuery(param);
        if (CollectionUtils.isEmpty(orderDOS)){
            return result;
        }
        List<Order> orders = orderDOS.stream().map(orderDO -> orderDO.toModel()).collect(Collectors.toList());
        //获取userIds
        List<Long> userIds = orders.stream().map(order -> order.getUserId()).collect(Collectors.toList());
        List<User> users = userService.queryUser(userIds);
        //组装user
        for (Order order:orders){
            for (User user:users){
                if (user.getId() == order.getUserId()){
                    order.setUser(user);
                }
            }
        }
        //获取productDetailIds
        List<String> productDetailIds = orders.stream().map(order -> order.getProductDetailId()).collect(Collectors.toList());
        List<ProductDetail> productDetails = productDetailService.queryProductDetail(productDetailIds);
        //组装productDetail
        for (Order order:orders){
            for (ProductDetail productDetail:productDetails){
                if (productDetail.getId().equals(order.getProductDetailId())){
                   order.setProductDetail(productDetail);
                }
            }
        }
        result.setData(orders);
        return result;
    }

    @Override
    public Order getByOrderNumber(String orderNumber) {
        if (StringUtils.isEmpty(orderNumber)){
            return null;
        }
        OrderDO orderDO = orderDAO.selectByOrderNumber(orderNumber);
        Order order = orderDO.toModel();

        return order;
    }

    @Override
    public Order updateOrderStatus(String orderNumber, OrderStatus orderStatus) {
        if (StringUtils.isEmpty(orderNumber)){
            return null;
        }
        OrderDO orderDO = orderDAO.selectByOrderNumber(orderNumber);
        if (orderDO ==null){
            return null;
        }
        orderDO.setOrderStatus(orderStatus.toString());
        orderDAO.updateByPrimaryKey(orderDO);
        return orderDO.toModel();
    }

    @Override
    public Order updateProductPersonNumber(String orderNumber) {
        if (StringUtils.isEmpty(orderNumber)){
            return null;
        }
        OrderDO orderDO = orderDAO.selectByOrderNumber(orderNumber);
        if (orderDO == null){
            return null;
        }
        //获取分布式锁
        RLock transferLock = redissonClient.getLock("PURCHASE");
        transferLock.lock();
        try {
            ProductDetail productDetail = productDetailService.getById(orderDO.getProductDetailId());
            if (productDetail == null){
                return null;
            }
            //库存-1
            productDetail.setStock(productDetail.getStock()-1);
            productDetailService.save(productDetail);
            Product product = productService.get(productDetail.getProductId());
            if (product == null){
                return null;
            }
            //购买人数+1
            product.setPurchaseNum(product.getPurchaseNum()+1);
            productService.save(product);
        }catch (Exception e){
           LOG.error("e is"+ e);
        }finally {
            transferLock.unlock();
        }
        return orderDO.toModel();
    }

    public String getAutoId() {

        //格式化格式为年月日
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        //获取当前时间
        String now = LocalDate.now().format(dateTimeFormatter);
        //通过redis的自增获取序号
        RAtomicLong atomicLong = redissonClient.getAtomicLong(now);
        atomicLong.expire(1, TimeUnit.DAYS);
        //拼装订单号
        return now + "" + atomicLong.incrementAndGet();

    }
}
